package ClassStudy;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author Cheng Jun
 * Description: 请输入描述
 * @version 1.0
 * @date 2021/8/21 22:30
 */
public class ClassAccessible {
    public static void main(String[] args) {
        try {
            Student student = new Student();
            long start = System.currentTimeMillis();
            for (int i = 0; i < 1_0000_0000; i++) {
                student.empty();
            }
            System.out.println(System.currentTimeMillis() - start + "正常调用花的时间");
            Class<?> aClass = Class.forName("ClassStudy.Student");
            Object studentObject = aClass.newInstance();
            Method empty = studentObject.getClass().getMethod("empty");
            // 必须是 public 修饰的变量！！！
            // Field nameField = studentObject.getClass().getField("name");
            Field ageField = studentObject.getClass().getField("age");
            studentObject.getClass().getDeclaredField("age");
            // 设置为 true 抑制检查，提高反射方法执行效率 25% 左右
            // A value of true indicates that the reflected object should suppress Java language access checking when it is used.
            empty.setAccessible(true);
            long startByReflection = System.currentTimeMillis();
            for (int i = 0; i < 1_0000_0000; i++) {
                empty.invoke(studentObject);
            }
            System.out.println(System.currentTimeMillis() - startByReflection + "反射方法调用花的时间");
        } catch (ClassNotFoundException | InstantiationException |
                IllegalAccessException | NoSuchMethodException | InvocationTargetException | NoSuchFieldException e) {
            e.printStackTrace();
        }
    }
}
